<template>
  <el-scrollbar ref="musicLyric">
      <p
        v-for="item in lyric"
        :key="item"
        :class="{
          active:
            musicCurrentTime * 1000 >= item.time &&
            musicCurrentTime * 1000 < item.pre,
        }"
      >
        {{ item.lrc }}
      </p>
  </el-scrollbar>
</template>

<script>
import { onMounted } from "@vue/runtime-core";
import { mapState, useStore } from "vuex";
import { ElScrollbar } from 'element-plus'
import { getLyric } from "../../request/ItemMusic/MusicData";
export default {
  mounted() {
    this.$store.dispatch(
      "getLyric",
      this.$store.state.playList[this.$store.state.playListIndex].id
    );
  },
  computed: {
    ...mapState(["lyricList", "musicCurrentTime", "playListIndex"]),
    lyric: function () {
      let arr;
      if (this.$store.state.playList[0].id != 0) {
        if (this.lyricList.lyric) {
          arr = this.lyricList.lyric.split(/[(\r\n)\r\n]+/).map((item, i) => {
            let min = item.slice(1, 3); //分钟
            let sec = item.slice(4, 6); //秒
            let mill = item.slice(7, 10); //毫秒
            let lrc = item.slice(11, item.length); //歌词
            let time =
              parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill);
            if (isNaN(Number(mill))) { //如果为空重新截取转换
              mill = item.slice(7, 9);
              lrc = item.slice(10, item.length);
              time =
                parseInt(min) * 60 * 1000 +
                parseInt(sec) * 1000 +
                parseInt(mill);
            }
            return { min, sec, mill, lrc, time };
          });
          arr.forEach((item, i) => { //判断最末尾的歌词
            if (i === arr.length - 1 || isNaN(arr[i + 1].time)) {
              item.pre = 100000;
            } else {
              item.pre = arr[i + 1].time;
            }
          });
        }
      }

      return arr;
    },
  },
  watch: {
    playListIndex: function () {
      this.$store.dispatch(
        "getLyric",
        this.$store.state.playList[this.$store.state.playListIndex].id
      );
    },
    musicCurrentTime: function (to) {
      // let p = document.querySelector("p.active");
      // if (p) {
      //   if (p.offsetTop > 300) {
      //     this.$refs.musicLyric.scrollTop = p.offsetTop - 300;
      //   }
      // }
      if (to === this.duration) {
        if (this.playListIndex === this.playList.length - 1) {
          this.updatePlayListIndex(0);
          this.play();
        } else {
          this.updatePlayListIndex(this.playListIndex + 1);
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
div {
  p {
    text-align: center;
    color: rgb(225, 227, 229);
  }
  .active {
    font-size: 20px;
    margin: 10px 0;
    font-weight: 700;
    color: rgb(0, 0, 0);
  }
}
</style>